//
//  OSSRequest.m
//  NiuNiuLawyer
//
//  Created by 曾永强 on 3/8/16.
//  Copyright © 2016 Beyondsoft. All rights reserved.
//

#import "OSS_Request.h"
#import "UIImage+TintColor.h"
@interface OSS_Request  ()

@end

@implementation OSS_Request

- (void)uploadFileSyscToOSSWithData:(NSDictionary<NSString *,NSData *> *)dictionary progressBlock:(OSSNetworkingMulUploadProgressBlock)uploadProgress completeHandler:(OSSMulCompleteBlock)completeBlock
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __block NSMutableArray *tempArray = [[NSMutableArray alloc]init];
        for (int i = 0 ; i < [dictionary count]; i++)
        {
            __block BOOL needBreak = NO;
            NSString *keyFileName = [[dictionary allKeys]objectAtIndex:i];
            NSData *fileData = [dictionary objectForKey:keyFileName];
//            UIImage *image = [UIImage imageWithData:fileData];
//            UIImage *newImage = [image imageWithCompressedMaxSize:1024];
//            NSData *data = UIImageJPEGRepresentation(newImage, 1.0);
            NSLog(@"start %@",@(i));
            [self uploadFileSyscToOSSWithData:fileData destinationFileName:keyFileName progressBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                uploadProgress(i,bytesSent,totalBytesSent,totalBytesExpectedToSend);
            } completeHandler:^(BOOL isSuccess, NSError *error, NSString *url) {
                if (isSuccess)
                {
                    [tempArray addObject:url];
                }else
                {
                    needBreak = YES;
                }
            }];
            
            if (needBreak)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completeBlock(NO,nil);
                });
                
                return;
                break;
            }
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            completeBlock(YES,tempArray);
        });
    });
}

//异步文件上传OK
- (void)uploadFileAsyscToOSSWithPath:(NSString *)localFilePath destinationFileName:(NSString *)oss_fileName progressBlock:(OSSNetworkingUploadProgressBlock)uploadProgress completeHandler:(OSSCompleteBlock)completeBlock
{
    OSSNWOperation *operation = [[OSSNWOperation alloc]init];
    operation.uploadProgress = uploadProgress;
    operation.ossMethod = OSS_REQUEST_METHOD_Async;
    operation.ossRecType = OSS_REC_TYPE_FILEPATH;
    operation.ossType = OSS_TYPE_UPLOAD;
    operation.localFilePath = localFilePath;
    operation.ossRemoteFileName = oss_fileName;
    operation.completeBlock = completeBlock;
    [operation sendRequest];

}


//异步data上传OK
- (void)uploadFileAsyscToOSSWithData:(NSData *)localFileData  destinationFileName:(NSString *)oss_fileName progressBlock:(OSSNetworkingUploadProgressBlock)uploadProgress completeHandler:(OSSCompleteBlock)completeBlock
{
    
    UIImage *image = [UIImage imageWithData:localFileData];
    UIImage *newImage = [image imageWithCompressedMaxSize:1024];
    NSData *data = UIImageJPEGRepresentation(newImage, 0.5);
    
    OSSNWOperation *operation = [[OSSNWOperation alloc]init];
    operation.uploadProgress = uploadProgress;
    operation.ossMethod = OSS_REQUEST_METHOD_Async;
    operation.ossRecType = OSS_REC_TYPE_DATA;
    operation.ossType = OSS_TYPE_UPLOAD;
    operation.resouceData = data;
    operation.ossRemoteFileName = oss_fileName;
    operation.completeBlock = completeBlock;
    [operation sendRequest];
    
}
//同步文件上传OK
- (void)uploadFileSyscToOSSWithPath:(NSString *)localFilePath destinationFileName:(NSString *)oss_fileName progressBlock:(OSSNetworkingUploadProgressBlock)uploadProgress completeHandler:(OSSCompleteBlock)completeBlock
{
    OSSNWOperation *operation = [[OSSNWOperation alloc]init];
    operation.uploadProgress = uploadProgress;
    operation.ossMethod = OSS_REQUEST_METHOD_Sync;
    operation.ossRecType = OSS_REC_TYPE_FILEPATH;
    operation.ossType = OSS_TYPE_UPLOAD;
    operation.localFilePath = localFilePath;
    operation.ossRemoteFileName = oss_fileName;
    operation.completeBlock = completeBlock;
    [operation sendRequest];
}
//同步data上传OK
- (void)uploadFileSyscToOSSWithData:(NSData *)localFileData  destinationFileName:(NSString *)oss_fileName progressBlock:(OSSNetworkingUploadProgressBlock)uploadProgress completeHandler:(OSSCompleteBlock)completeBlock
{
    
    UIImage *image = [UIImage imageWithData:localFileData];
    UIImage *newImage = [image imageWithCompressedMaxSize:1024];
    NSData *data = UIImageJPEGRepresentation(newImage, 0.5);
    
    OSSNWOperation *operation = [[OSSNWOperation alloc]init];
    operation.uploadProgress = uploadProgress;
    operation.ossMethod = OSS_REQUEST_METHOD_Sync;
    operation.ossRecType = OSS_REC_TYPE_DATA;
    operation.ossType = OSS_TYPE_UPLOAD;
    operation.resouceData = data;
    operation.ossRemoteFileName = oss_fileName;
    operation.completeBlock = completeBlock;
    [operation sendRequest];

    
}
//异步下载
- (void)downloadFileAsyscWithOSSUrl:(NSString *)ossUrl toLocalPath:(NSString *)localFilePath progressBlock:(OSSNetworkingDownloadProgressBlock)downloadProgress completeHandler:(OSSCompleteBlock)completeBlock
{
    if (localFilePath == nil)
    {
        localFilePath = [OSS_Request getDocPath];
    }
    OSSNWOperation *operation = [[OSSNWOperation alloc]init];
    operation.ossMethod = OSS_REQUEST_METHOD_Async;
    operation.ossType = OSS_TYPE_DOWNLOAD;
    operation.downloadProgress = downloadProgress;
    operation.downloadToFileURL = [NSURL fileURLWithPath:[localFilePath stringByAppendingPathComponent:[ossUrl lastPathComponent]]];
    operation.downloadRemoteFileName = [ossUrl lastPathComponent];
    operation.completeBlock = completeBlock;
    [operation sendRequest];
}
//同步下载
- (void)downloadFileSyscWithOSSUrl:(NSString *)ossUrl toLocalPath:(NSString *)localFilePath progressBlock:(OSSNetworkingDownloadProgressBlock)downloadProgress completeHandler:(OSSCompleteBlock)completeBlock
{
    if (localFilePath == nil)
    {
        localFilePath = [OSS_Request getDocPath];
    }
    OSSNWOperation *operation = [[OSSNWOperation alloc]init];
    operation.ossMethod = OSS_REQUEST_METHOD_Sync;
    operation.ossType = OSS_TYPE_DOWNLOAD;
    operation.downloadProgress = downloadProgress;
    operation.downloadToFileURL = [NSURL fileURLWithPath:[localFilePath stringByAppendingPathComponent:[ossUrl lastPathComponent]]];
    operation.downloadRemoteFileName = [ossUrl lastPathComponent];
    operation.completeBlock = completeBlock;
    [operation sendRequest];
}


- (void)dealloc
{
    NSLog(@"oss_request dealloc");
}
/*
- (void)test
{
    NSData * data = UIImageJPEGRepresentation([UIImage imageNamed:@"normal_release_icon"], 0.7);
    [[[OSS_Request alloc]init]uploadFileSyscToOSSWithPath:[kDocumentPath stringByAppendingPathComponent:@"file1m"] destinationFileName:@"normal_release_icon_test5.data"];
    [[[OSS_Request alloc]init]downloadFileSyscWithOSSUrl:@"normal_release_icon_test5.data" toLocalPath:kDocumentPath];
    
}
 */

+ (BOOL)isExistAtLocalWithFileName:(NSString *)fileName withFileSize:(NSString *)fileSizeString;//用于判断文件是否下载完整
{
    if (fileName.length == 0)
    {
        return NO;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [[self getDocPath]stringByAppendingPathComponent:fileName];
    BOOL success = [fileManager fileExistsAtPath:filePath];
    if (success)
    {
        if (ABS([fileSizeString longLongValue] - [self fileSizeAtPath:filePath]) > 1*1024)
        {//文件不完整 若误差超过1k  则需重新下载 
            BOOL removeFileSuccess = NO;
            NSError *error = nil;
            removeFileSuccess = [fileManager removeItemAtPath:filePath error:&error];//删除旧文件
            NSLog(@"本地文件未下载完整,删除原文件");
            return NO;
        }
    }
    
    return success;
}




+ (NSString *)getDocPath
{
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [kDocumentPath stringByAppendingPathComponent:@"docPath"];
    BOOL success = [fileManager fileExistsAtPath:path];
    if (!success)
    {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
    }
    [self addSkipBackupAttributeToItemAtURL:path];
    return path;
}
//单个文件的大小

+ (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath])
    {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSString *)path
{
    NSURL *URL = [NSURL fileURLWithPath:path];
    assert([[NSFileManager defaultManager] fileExistsAtPath:[URL path]]);
    NSError *error = nil;
    BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES]
                                  forKey:NSURLIsExcludedFromBackupKey
                                   error:&error];
    if (!success) {
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}

@end
